/**
 * @filename LoginController.java
 */
package com.liupf.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.liupf.common.utils.MD5Util;
import com.liupf.common.utils.SmsUtil;
import com.liupf.common.utils.TypeConstant.OrderType;
import com.liupf.interceptor.ExceptionInterceptor;
import com.liupf.interceptor.SessionInViewInterceptor;
import com.liupf.userData.User;

/**
 * @description 登录相关
 * @author shevliu
 * @email shevliu@gmail.com Jul 27, 2012 10:10:45 PM
 */

public class LoginController extends Controller {

	private Log log = LogFactory.getLog(this.getClass());


	public void index() {
	}

	@ClearInterceptor(ClearLayer.ALL)
	@Before({ExceptionInterceptor.class , SessionInViewInterceptor.class})
	public void login() {
		try {
			String userName = getPara("username");
			String password = MD5Util.MD5(getPara("password"));
			log.debug(userName + "  " + password);
			User user=new User();
			Record rec = Db
					.findFirst(
							"select u.id,u.company,u.purview,u.user_role,t.companyname,t.city,t.new_city_id, t.message_num,t.recharge_money,u.lock FROM sys_user u LEFT JOIN tel_company t ON t.company=u.company where u.user_name = ?  and  u.password = ? and u.status=1",
							userName, password);
			user.setId(rec.getInt("id"));
			user.setCompany(rec.getStr("company"));
			user.setPurview(rec.getInt("purview"));
			user.setUserRole(rec.getStr("user_role"));
			String companyname = rec.getStr("companyname");
			String syscity = rec.getStr("city");
			Integer cityId = rec.getInt("new_city_id");
			Integer messageNum = rec.getInt("message_num");
			float money=rec.getFloat("recharge_money");
			int lock=rec.getInt("lock");
			
			if (user.getId() != 0) {
			    if(money<100f && !rec.getStr("user_role").equals("admin"))
			        throw new RuntimeException("公司余额不足100，请充值后登陆");
			    if(lock==1)
			    	  throw new RuntimeException("该账户已被锁定，请联系管理员");
				System.out.println("login id:  " + user.getId());
				System.out.println("login company:  " + user.getCompany());
				System.out.println("login purview:  " + user.getPurview());
				Db.update("update sys_user set last_login = ? where id = ?" , new Date() , user.getId());
				getSession().setAttribute("userId", user.getId());
				getSession().setAttribute("userName", userName);
				getSession().setAttribute("company", user.getCompany());
				getSession().setAttribute("purview", user.getPurview());
				getSession().setAttribute("myCompanyName", companyname);
				getSession().setAttribute("cityId", cityId+"");
				getSession().setAttribute("syscity", syscity);
				getSession().setAttribute("userRole", user.getUserRole());
				if(user.getPurview()==0)
				{
					String smsNum=SmsUtil.getSmsBalanceToGateway();
					getSession().setAttribute("SmsNum", smsNum);
				}
				
				String sql = "select * from tel_company ";
				List<Record> list = Db.find(sql);
				
				getSession().setAttribute("telLists", list);
				
				OrderType[] orderTypeList = OrderType.values();
				List<Map<String,String>> orderTypeMapList = new ArrayList<Map<String,String>>();
				for(OrderType orderType : orderTypeList){
					Map<String,String> returnMap = new HashMap<String, String>();
					returnMap.put("value", orderType.name());
					returnMap.put("name", orderType.getTypeName());
					
					orderTypeMapList.add(returnMap);
				}
				getSession().setAttribute("orderTypeMapList", orderTypeMapList);
				
				//String userMessage = "SELECT COUNT(*) as num FROM tel_company_message WHERE create_time >DATE_ADD(CURDATE(),INTERVAL -DAY(CURDATE())+1 DAY) AND create_time<LAST_DAY(CURDATE()) AND COMPANY='"+user.getCompany()+"'";
				//long messageUserCount = Db.findFirst(userMessage).getLong("num");
				
				//String totalMessage = "SELECT ifnull(message_num,0) as num FROM tel_company where COMPANY='"+user.getCompany()+"'";
				//long messageTotalCount = Db.findFirst(totalMessage).getLong("num");
				
				String chargemessage=Db.queryStr("select recharge_message from tel_company where company='"+user.getCompany()+"'");
				getSession().setAttribute("companyMessage", chargemessage);
				
				getSession().setAttribute("messageLeftCount", messageNum);
	
				redirect("/my");
			} else {
				throw new RuntimeException("登录失败，请重试");
			}
		} catch (Exception e) {
			log.error("登录失败：" + e) ;
			throw new RuntimeException("登录失败，请重试:"+e.getMessage() , e);
		}
	}

	public void logout() {
		getSession().invalidate();
		redirect("/login.html");
	}

	


}
